<?php

namespace Workerman\Protocols;

use Workerman\Connection\TcpConnection;


class Msg
{
    public static $Key          =   'dasdejaf33534@#$!^fcd';
    public static $EndSymbol    =   "\n";


    public static function input($buffer, TcpConnection $connection)
    {
        echo $buffer;
        if( strlen($buffer)<32 ){
            return 0;
        }

        if( strlen($buffer)>TcpConnection::$maxPackageSize ){
            return 0;
        }

        if( strpos($buffer, md5(self::$Key.(strlen($buffer)-33)))!==false ){
            return 0;
        }
        $pos = strpos($buffer, self::$EndSymbol);
        if ($pos === false) {
            return 0;
        }
        return $pos+1;
    }
    /**
     * Encode.
     *
     * @param string $buffer
     * @return string
     */
    public static function encode($buffer)
    {
        $data = base64_encode(gzcompress($buffer));
        return md5(self::$Key.strlen($data)) . $data . self::$EndSymbol;
    }

    /**
     * Decode.
     *
     * @param string $buffer
     * @return string
     */
    public static function decode($buffer)
    {
        return gzuncompress(base64_decode(substr($buffer, 32, -1)));
    }
}
